var contactCommandNamespace = contactCommandNamespace || {};

contactCommandNamespace.ContactCommand = function (primaryControl) {
    //debugger;
    var formContext = primaryControl;

    var telephone1 = formContext.getAttribute("telephone1").getValue();

    if (telephone1)
        return true;
    else
        return false;
}


/**
 * Utility object for displaying and managing a progress indicator in Dynamics 365 using Xrm.Utility.
 *
 * @namespace ProgressIndicato
 * @property {function(string): void} show - Displays the progress indicator with the specified message.
 * @property {function(): void} hide - Hides the currently displayed progress indicator.
 * @property {function(string, function): Promise<any>} withProgress - Shows the progress indicator with the given message,
 * executes the provided asynchronous function, and hides the indicator when the function completes (success or failure).
 * @example
 * ProgressIndicato.withProgress("Processing...", () => {
 *   // Your async code here
 *   return someAsyncOperation();
 * });
 */
var wrapProgressIndicator={
    show: function (msg) {
        Xrm.Utility.showProgressIndicator(msg);
    },
    hide: function () {
        Xrm.Utility.closeProgressIndicator();
    },
    /*
    * 包装一个异步函数，显示进度指示器，执行函数，并在完成后隐藏指示器
    * @param {string} msg - 进度提示语 
    * @param {function} asyncFunc - 返回 Promise 的异步函数
    * @returns {Promise<any>} - 返回一个 Promise，表示异步操作的结果
    */
    wrap: (msg, asyncFunc) =>{
        wrapProgressIndicator.show(msg);
        return Promise.resolve()
            .then(asyncFunc)
            .finally(() => {
               wrapProgressIndicator.hide();
            });
    }
}

/**
 * 通用带进度条的异步操作封装
 * @param {string} msg - 进度提示语
 * @param {Function} asyncFunc - 返回 Promise 的异步函数
 * @returns {Promise<any>}
 */
function withProgressIndicator(msg, asyncFunc) {
    Xrm.Utility.showProgressIndicator(msg);
    return Promise.resolve()
        .then(asyncFunc)
        .finally(() => {
            Xrm.Utility.closeProgressIndicator();
        });
}

// 假设 safeAwait 已定义
async function safeAwait(promise, fallback = null) {
    try {
        return await promise;
    } catch (error) {
        console.error('执行失败:', error);
        return fallback;
    }
}

contactCommandNamespace.onClick = async function (primaryControl) {

    let loadingmsg = contactCommandNamespace.getLangString("loadingmsg");
    //Xrm.Utility.showProgressIndicator(loadingmsg);
    let formContext = primaryControl;
    let id = formContext.data.entity.getId();
    let entityName = formContext.data.entity.getEntityName();
    //let data = `&data=${encodeURIComponent("id=" + id + "&entityName=" + entityName)}`

    // 添加时间戳防止缓存
    const timestamp = Date.now();
    const webresourceName = `qzw_/html/contactpage.html`;
     debugger;

    await safeAwait(
        wrapProgressIndicator.wrap(loadingmsg, async () => {
            await Xrm.Navigation.navigateTo({
                pageType: "webresource",
                webresourceName: webresourceName,
                data: JSON.stringify({ id: id, entityName: entityName, t: timestamp })
            }, {
                target: 2,
                width: { value: 80, unit: "%" },
                height: { value: 80, unit: "%" },
                title: entityName
            });
            console.log("导航到自定义页面成功");
        }),
        null // 失败时返回 null，可自定义
    );

   
    // Xrm.Navigation.navigateTo({
    //     pageType: "webresource",
    //     webresourceName: webresourceName,
    //     data: JSON.stringify({id: id, entityName: entityName,t: timestamp})
    // }, {
    //     target: 2, // 2 = 新窗口
    //     width: { value: 80, unit: "%" },
    //     height: { value: 80, unit: "%" },
    //     title: entityName
    // }).then(
    //     function () {
    //         console.log("导航到自定义页面成功");
    //         Xrm.Utility.closeProgressIndicator();
    //     },
    //     function (error) {
    //         console.error("导航失败: " + error.message);
    //     }
    // );
}

contactCommandNamespace.getLangString = function (key) {
    let lcid = Xrm.Utility.getGlobalContext().userSettings.languageId;
    let resourcePath = `qzw_/resxs/ss_lang_${lcid}`;
    return Xrm.Utility.getResourceString(resourcePath, key);
}